import logging

from django.contrib.auth.backends import ModelBackend

from ERP_5.utils.cache_permissions import cache_permissions_by_user
from erp_system.models import UserModel

logger = logging.getLogger('my')


class UserLoginAuth(ModelBackend):
    """
    重新用户登录（认证）
    """

    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = UserModel.objects.get(username=username)
        except Exception as ex:
            logger.error(ex)
            return None

        # 判断密码
        if user and user.check_password(password):
            # 缓存用户的权限
            cache_permissions_by_user(user)
            return user
        return None
